package com.ruoyi.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.EqpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.vo.WebSocketVO;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ehcache.EqpStatusCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.websocket.WebSocketUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.prt.service.IPrtEpLogService;
import com.ruoyi.prt.service.IPrtPrintService;
import com.ruoyi.prt.service.IPrtUserDocService;
import com.ruoyi.web.core.config.PropertiesUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;

//@Component
public class  MqttConsumerCallback implements MqttCallbackExtended  {
    private final MqttClient client;
    private final MqttConnectOptions options;
    private final String[] topic;
    private final int[] qos;

    private static final IPrtUserDocService prtUserDocService = SpringUtils.getBean(IPrtUserDocService.class);
    private static final IPrtPrintService prtPrintService = SpringUtils.getBean(IPrtPrintService.class);
    private static final TokenService tokenService = SpringUtils.getBean(TokenService.class);


    public MqttConsumerCallback(MqttClient client, MqttConnectOptions options, String[] topic, int[] qos) {
        this.client = client;
        this.options = options;
        this.topic = topic;
        this.qos = qos;
    }

    /**
     * 断开重连
     */
    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("MQTT_连接断开，发起重连");
        try {
            if (null != client && !client.isConnected()) {
                client.reconnect();
                System.out.println("MQTT_尝试重新连接");
            } else {
                client.connect(options);
                System.out.println("MQTT_尝试建立新连接");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收到消息调用令牌中调用
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("MQTT_接收到消息调用令牌中调用" + Arrays.toString(topic));
    }

    /**
     * 消息处理
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        try {
            String msg = new String(message.getPayload());
            JSONObject jsonObject = JSON.parseObject(msg);
            int state = jsonObject.getInteger("state");

            AjaxResult result = AjaxResult.success().setData(msg);
            switch (state){
                case 0:
                    EqpStatusCache.setEqpStatus(jsonObject.getString("name"), EqpStatus.CONNECTED);
                    break;
                case 7:
                    result.put("status", 7);
                    WebSocketUtils.sendMessage(jsonObject.getString("token"), JSON.toJSONString(result));
                    break;
                case 8:
                    result.put("status", 8);
                    WebSocketUtils.sendMessage(jsonObject.getString("token"), JSON.toJSONString(result));
                    break;
                case 9:
                    String token = jsonObject.getString("token");

                    //4.扣费（接Service里的流程）
                    WebSocketVO data = new WebSocketVO();
                    if (jsonObject.containsKey(Constants.DATA)) {
                        data = jsonObject.getObject(Constants.DATA, WebSocketVO.class);
                    }
                    result = prtPrintService.deductionBalance(tokenService.getLoginUser(token).getUser(), data);
                    WebSocketUtils.sendMessage(token, JSON.toJSONString(result));
                    break;
            }

            System.out.println("MQTT_收到topic:" + topic + " 消息:" + msg);
        } catch (Exception e) {
            System.out.println("MQTT_处理消息异常:" + e);
        }
    }

    /**
     * mqtt连接后订阅主题
     */
    @Override
    public void connectComplete(boolean b, String s) {
        try {
            if (null != topic && null != qos) {
                if (client.isConnected()) {
                    client.subscribe(topic, qos);
                    System.out.println("MQTT_服务连接成功，客户端ID:" + PropertiesUtil.MQTT_CLIENT_ID);
                    System.out.println("MQTT_订阅主题:" + Arrays.toString(topic));
                } else {
                    System.out.println("MQTT_服务连接失败，客户端ID:" + PropertiesUtil.MQTT_CLIENT_ID);
                }
            }
        } catch (Exception e) {
            System.out.println("MQTT_订阅主题异常:" + e);
        }
    }
}
